const Request = require('request')
const cheerio = require('cheerio')
const iconv = require('iconv-lite')

let urls = [
    'https://www.dy2018.com/i/102811.html',
    'https://www.dy2018.com/i/102812.html',
    'https://www.dy2018.com/i/102813.html',
    'https://www.dy2018.com/i/102814.html',
    'https://www.dy2018.com/i/102815.html',
]

/*
const getRequest = (url, callback) => {
    let options = {
        url,
        encoding: null
    }
    Request(url, options, callback)
}


for (let i = 0; i < urls.length; i++) {
    getRequest(urls[i], (err, res, body) => {
        let html = iconv.decode(body, 'gb2312')
        let $ = cheerio.load(html)
        let video = {
            title: $('.title_all h1').text(),
            img:  $('#Zoom img').attr('src'),
        }
        console.log(video)
    })
}
*/

const puppeteer = require('puppeteer')

let sleep = (num) => new Promise((resolve) => {
    setTimeout(() => {
        resolve()
    }, num * 3)
})

const getVideoInfo = async (url) => {
    let browser = await puppeteer.launch()
    let page = await browser.newPage()
    await page.goto(url, {
        waitUntil: 'networkidle2'
    })

    await sleep(Math.random() * 1e5)

    let res = await page.evaluate(() => {
        // 在虚拟浏览器中执行
        let $ = window.$
        let title = $('.title_all h1').text()
        return {
            title
        }
    })
    await browser.close()
    return res
}

;(async () => {
    for (let i = 0; i < urls.length; i++) {
        let info = await getVideoInfo(urls[i]);
        console.log(info)
    }
})()
